import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import http from '../../api/http';
import { Button, Input, message, Modal, Space } from 'antd';
import { Divider, List, Typography } from 'antd';

const { TextArea } = Input;

function Index() {
  const { id } = useParams();
  // console.log(id,'详情');

  // 定义详情数据
  const [detail, setDetail] = useState([])
  const [value, setValue] = useState('');
  const [value1, setValue1] = useState('');

  // 获取接口数据
  const fetchDetail = async () => {
    const res = await http.get(`/article/${id}`);
    console.log(res, '详情列表');
    setDetail(res.data)
  }

  // 回调
  useEffect(() => {
    fetchDetail()
  }, [])

  // 发表评论 
  const navigate = useNavigate()
  const handleSend = async () => {
    // 如果没有token
    let token = localStorage.getItem('token')
    if (!token) {
      message.error('未登录，请先登录!');
      navigate('/login')
    }
    // 不能为空
    if(!value.trim()){
      message.error('不能为空');
      setValue('')
      return
    }
    // 如果字数超过100字
    if(value.length>100){
      setValue('');
      message.error('字数不得超过100字')
      return
    }
    // 发送不雅文字时
    const newValue = value.replace(/傻逼|笨蛋|蠢货|二货|脑残|贱人/g,'**')
    const res = await http.post('/discuss', {
      userId: 47529555,// 47529555 用户id
      content: newValue,
      articleId: Number(id)
    })
    console.log(res, '发送评论');
    setValue('')
    fetchDetail()
    message.success('评论成功')
  }

  // 回复评论
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const handleOk = async () => {
    // 不能为空
    if(!value1.trim()){
      message.error('不能为空');
      setValue1('')
      return
    }
    const res = await http.post('/discuss', {
      userId: 47529555,// 47529555 用户id
      content: value1,
      articleId: Number(id),
      commentId: open.commentId
    })
    console.log(res, '回复评论');
    setValue1('')
    fetchDetail()
    message.success('回复成功')
    setOpen(false)
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };

  return (
    <div>
      <div>
        <div>
          <span className='text-2xl'>标题:</span>
          <h1 className='text-3xl'>{detail.title}</h1>
          <p className='font-extralight'>
            创建时间: {detail.createdAt}
            <span style={{ marginLeft: '20px' }}>浏览量: {detail.viewCount}</span>
          </p>
          <span className='text-2xl'>内容:</span>
          <p className='font-extralight'>
            &ensp;&ensp;&ensp;&ensp;{detail.content}
          </p>
          <br />
          <hr />
        </div>
        {/* 输入框 */}
        <TextArea
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder="请输入进行评论..."
          autoSize={{ minRows: 3, maxRows: 5 }}
        />
        <Button onClick={() => handleSend()} size='large' color="primary" variant="filled">
          发送评论
        </Button>
        <br />
        <br />
        <hr />
        <br />
        <h1 className='text-2xl'>评论区:</h1>
        <List
          dataSource={detail.comments}
          renderItem={(item) => (
            <div>
              <Space align='start'>
                <img style={{ width: '40px', height: '40px', borderRadius: '50%' }} src="https://tse2-mm.cn.bing.net/th/id/OIP-C.rXzfx0d5tsJB6W5sw4Nt0gHaHa?w=192&h=192&c=7&r=0&o=7&dpr=1.1&pid=1.7&rm=3" alt="" />
                <div>
                  <div>
                    {item.user.username}
                    <span className='mx-1'>{item.user.createdAt}</span>
                  </div>
                  <span className='px-0.5'>{item.content}</span>
                  <Button onClick={() => setOpen({ username: item.user.username, commentId: item.id })} color="pink" variant="filled">回复</Button>
                  {
                    item.replies && item.replies.length > 0 && (
                      <List
                        dataSource={item.replies}
                        renderItem={(it) => (
                          <div>
                            <Space align='start'>
                              <img style={{ width: '40px', height: '40px', borderRadius: '50%' }} src="https://tse2-mm.cn.bing.net/th/id/OIP-C.EgxVZ4qkujt-VgjiAPlitwAAAA?w=198&h=198&c=7&r=0&o=7&dpr=1.1&pid=1.7&rm=3" alt="" />
                              <div>
                                <div>
                                  {it.user.username}
                                  <span className='mx-1'>{it.user.createdAt}</span>
                                </div>
                                <span className='px-0.5'>{it.content}</span>

                              </div>
                            </Space>
                          </div>
                        )}
                      />
                    )
                  }
                </div>
              </Space>
            </div>
          )}
        />
      </div>
      <Modal
        title="Title"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <TextArea
          value={value1}
          onChange={(e) => setValue1(e.target.value)}
          placeholder="请输入进行回复..."
          autoSize={{ minRows: 3, maxRows: 5 }}
        />
      </Modal>
    </div>
  )
}

export default Index
